#include<iostream>
#include <sys/types.h>          
#include <sys/socket.h>
#include<string.h>
#include<unistd.h>
#include<netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
using namespace std;

#define PORT 8112
#define MESSAGE_LEN 1024

int main(){
	int socket_fd;
	int ret=-1;
	
	
	struct sockaddr_in localaddr;
	localaddr.sin_family=AF_INET;
        localaddr.sin_port=PORT;
        localaddr.sin_addr.s_addr=INADDR_ANY;//INADDR_ANY==0
        bzero(&(localaddr.sin_zero),8);

	
        struct sockaddr_in clientaddr;
	int len=sizeof(localaddr);

        char send_buff[MESSAGE_LEN]={0,};
	char recv_buff[MESSAGE_LEN]={0,};

	socket_fd=socket(AF_INET,SOCK_DGRAM,0);
	if(socket_fd==-1){
                cout<<"failed to create socket!"<<endl;
                exit(-1);
        }
	/*ret=setsockopt(socket_fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); //set socket option
        if(ret==-1){
                cout<<"failed to set socket option"<<endl;
        }*/
	
        

        ret=bind(socket_fd,(struct sockaddr *)&localaddr,sizeof(localaddr));
        if(ret==-1){
                cout<<"failed to bind addr and port!"<<endl;
                exit(-1);
        }
	while(1){
		ret=recvfrom(socket_fd,recv_buff,MESSAGE_LEN-1,0,(struct sockaddr *) &localaddr, (socklen_t*)&len);
		if(ret==0){
                        cout<<"client don't send data,disconnected"<<endl;
                        break;
                }
		//recv_buff[ret]=0;
                cout<<"recveived data is:"<<recv_buff<<endl;
                sendto(socket_fd,recv_buff,MESSAGE_LEN,0,(struct sockaddr *) &localaddr, len);		
	}
	close(socket_fd);
	return 0;
}
